var mgeRole = {
    tableid: "table1",
    layerindex: null,
    bsTable: null,
    idselect: null,
    layoutopt: null
};
mgeRole.openDlg = function (title) {
    var hei = $(window).height() - 20;
    var wi = $(window).width() - 20;
    layer.open({
        type: "1",
        title: title ? title : "添加",
        area: [(wi > 650 ? 650 : wi) + 'px', (hei > 500 ? 500 : hei) + 'px'],
        shade: 0.4,
        maxmin: true,
        btn: ["确定", "取消"],
        content: $("#roleopt"),
        scrollbar: false,
        success: function (layero, index) {
            if (!mgeRole.layoutopt) {
                $("#roleopt").parent().height();
                $("#layrole").layout({
                    west__size: '48%'
                    , west__minSize: 270
                    , west__maxSize: 400
                });
                $("#menu_tree").height($("#menu_tree").parent().height() - 10);
            }
        },
        yes: function (index) {
            $("#form_opt").submit();
            //mgeRole.postAjaxFrom();
            mgeRole.layerindex = index;
        }, btn2: function (index) {
            mgeRole.clearInputs();
        }, cancel: function () {
            mgeRole.clearInputs();
        }
    });
};
mgeRole.menuTree = function () {
    $.fn.zTree.init($("#menu_tree"), {
        view: {
            dblClickExpand: false
        }, data: {
            simpleDate: {
                enable: true
            }
        },
        check: {
            chkboxType: {"Y": "ps", "N": "ps"},
            chkStyle: "checkbox",
            enable: true
        }, async: {
            enable: true, url: ctx + "/mge/adx/treefunc?type=fuc", dataFilter: function (treeid, parentNode, respsnseData) {
                if (respsnseData != null && respsnseData.code == "200") {
                    if (parentNode == null) {
                        var data = [
                            {
                                id: 0, name: "功能目录", children: respsnseData.data
                            }
                        ];
                        return data;
                    } else {
                        return respsnseData.data;
                    }
                }
                return [
                    {}
                ];
            }, autoParam: ["id"]
        }, data: {}, callback: {
            beforeClick: function (treeId, treeNode) {
                return true;
            }, onCheck: function (e, treeId, treeNode) {
                var zTree = $.fn.zTree.getZTreeObj("menu_tree"),
                    nodes = zTree.getCheckedNodes(true),
                    v = "";
                var bbs = []
                for (var i = 0, l = nodes.length; i < l; i++) {
                    v += nodes[i].name + ",";
                    if (nodes[i].id != "0") {
                        bbs.push(nodes[i].id);
                    }
                }
                $("#menus").val(bbs);
            }
        }
    });
}
mgeRole.clearInputs = function () {
    var ipts = $("#form_opt").find("[data-type='rep']");
    if (ipts.length > 0) {
        ipts.each(function (i, v) {
            $(v).val("");
            var er = $(v).next();
            if (er != null && $(er).length > 0 && $(er).prop("nodeName").toLowerCase() == "em") {
                er.remove();
                var hs = $(v).parents(".col-md-8");
                hs.removeClass("has-success");
                hs.removeClass("has-error");
            }
        });
    }
    mgeRole.treeCheckNo();
}
mgeRole.treeCheckNo = function () {
    var zTree = $.fn.zTree.getZTreeObj("menu_tree");
    zTree.checkAllNodes(false);
}
mgeRole.initColumn = function () {
    return [[{
        field: 'selectItem', radio: true
    }, {
        title: '角色id', field: 'roleId', width: "100px", align: 'center', valign: 'middle'
    }, {
        title: '角色名称', field: 'roleName', width: "200px", align: 'center', valign: 'middle', formatter: function (v) {
            return v;
        }
    }, {
        title: '角色描述', field: 'remark', width: "150px", align: 'center', valign: 'middle', formatter: function (v) {
            return v;
        }
    }, {
        title: '创建时间', field: 'createTime', width: "150px", align: 'center', valign: 'middle', formatter: function (v) {
            return v;
        }
    }]];
}
mgeRole.queryParams = function () {
    return cmm.serializeObject($("#form_search"));
}
mgeRole.resHeigth = function () {
    var he = $(window).height() - ($("#divsearch").height() + 20);
    return he;
}
mgeRole.addOnClick = function () {
    $("#add").on("click", function (e) {
        e.preventDefault();
        $("#roleId").val("");
        $("#menus").val("");
        mgeRole.treeCheckNo();
        mgeRole.openDlg();
    });
}
mgeRole.updateOnClick = function () {
    $("#update").on('click', function (e) {
        e.preventDefault();
        var row = mgeRole.bsTable.getSelections();
        if (row == null && row.length == 0) {
            layer.alert("请选中您要修改数据！");
        }
        mgeRole.openDlg("修改");
        mgeRole.getByRoleid(row[0].roleId);

    });
}
mgeRole.getByRoleid = function (id) {
    var lay = layer.load({shade: [0.1]});
    $.ajax({
        url: ctx + "/mge/adx/getRoleid",
        data: {roleid: id},
        dataType: "json",
        type: 'post',
        success: function (d, s) {
            layer.close(lay);
            if (d.code == '200') {
                cmm.fromData(d.data.role);
                if (d.data.menus != null) {
                    $("#menus").val(d.data.menus.join(","));
                }
                var ztree = $.fn.zTree.getZTreeObj("menu_tree");
                var nodes = ztree.getNodes();
                var ps = d.data.menus;
                var psobj = {};
                var funct = [];
                for (var s in ps) {
                    psobj[ps[s]] = true;
                }
                mgeRole.dgNode(nodes, psobj, ztree, funct);
                $("#form_opt").valid();
            } else {
                layer.alert(d.message);
            }
        }, error: function (sta) {
            layer.close(lay);
            layer.alert("请求失败，请重试或检查网络！");
        }
    });
}
mgeRole.delOnClick = function () {
    $("#del").on('click', function (e) {
        e.preventDefault();
        var row = mgeRole.bsTable.getSelections();
        if (row == null || row.length == 0) {
            layer.alert("请选中您要修改数据！");
            return false;
        }
        layer.confirm("您确定要删除数据吗？", {title: ["确认", "font-size:14px;font-weight:bold;"]}, function () {
            var lay = layer.load({shade: [0.1]});
            $.ajax({
                url: ctx + "/mge/adx/delRole", data: {id: row[0].roleId}, type: "post", dataType: "json", success: function (data, sta) {
                    layer.close(lay);
                    if (data != null && data.code == '200') {
                        cmm.layerMessge("删除成功");
                        mgeRole.refresh();
                    }
                }, error: function (sta) {
                    layer.close(lay);
                    layer.alert("请求失败，请重试或检查网络！");
                }
            })
        }, function () {

        });
    });

}
mgeRole.dgNode = function (nodes, ps, ztree, fntx) {
    for (var i = 0; i < nodes.length; i++) {
        var no = nodes[i];
        if (no.id == '0' && !no.checked) {
            no.checked = true;
            ztree.updateNode(no);
        }
        if (no.children.length == 0) {
            // for (var j = 0; j < ps.length; j++) {
            var nn = ps[no.id];
            if (nn != null && nn == true) {
                no.checked = true;
                ztree.updateNode(no);
                //  ztree.checkNode(no, true, true);
            }
            //}
        } else {
            mgeRole.dgNode(no.children, ps, ztree, fntx);
            var nn = ps[no.id];
            if (nn != null && nn == true) {
                no.checked = true;
                ztree.updateNode(no);
                //  ztree.checkNode(no, true, true);
            }
        }
    }
}
mgeRole.postAjaxFrom = function () {
    $("#form_opt").validate({
        rules: {
            roleName: {
                "required": true, maxlength: 20, textChvail: true, remote: {
                    type: 'post',
                    url: ctx + "/mge/adx/ckrolename",
                    data: {
                        rolename: function () {
                            return $("#roleName").val();
                        }, id: function () {
                            return $("#roleId").val();
                        }
                    },
                    dataType: 'html',
                    dataFilter: function (dd, type) {
                        var data = JSON.parse(dd);
                        if (data.code == 200 && data.data == true) {
                            return true;
                        } else {
                            return false;
                        }
                    }
                }
            },
            remark: {"required": true, maxlength: 100, textChvail: true},
        }, messages: {
            roleName: {"required": "请输入角色名", maxlength: "最大20字符", remote: "角色名不可用"},
            remark: {"required": "请输入描述", maxlength: "最大100字符"},
        }, success: function (label) {

        }, onkeyup: function (element) {
            $(element).valid();
        }, onfocusout: false, errorElement: "em", errorPlacement: function (error, element) {
            $(error).css({"color": "red", "font-size": "15px"});
            $(element).parent().append(error);
        }, highlight: function (element, errorClass, validClass) {
            $(element).parents(".col-md-8").addClass("has-error").removeClass("has-success");
        }, unhighlight: function (element, errorClass, validClass) {
            $(element).parents(".col-md-8").addClass("has-success").removeClass("has-error");
        }, submitHandler: function () {
            if (!$("#form_opt").valid()) {
                return false;
            }
            mgeRole.ajax();
            return false;
        }
    });
}
mgeRole.refresh = function (pageNumber) {
    mgeRole.bsTable.refresh(mgeRole.queryParams(), pageNumber);
}
mgeRole.load = function () {
    mgeRole.bsTable.load(mgeRole.queryParams());
}
mgeRole.ajax = function () {
    var lay = layer.load(0, {shade: [0.1]});
    if ($("#roleId").val() == "") {
        $.ajax({
            url: ctx + "/mge/adx/addRole",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeRole.layerindex);
                mgeRole.clearInputs();
                if (data.code == '200') {
                    mgeRole.refresh(1);
                    cmm.layerMessge("添加成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    } else {
        $.ajax({
            url: ctx + "/mge/adx/updateRole",
            data: $("#form_opt").formSerialize(),
            type: "post",
            dataType: "json",
            success: function (data, stat, jqh) {
                layer.close(lay);
                layer.close(mgeRole.layerindex);
                mgeRole.clearInputs();
                if (data.code == '200') {
                    mgeRole.refresh();
                    cmm.layerMessge("修改成功！");
                } else {
                    layer.alert(data.message);
                }
            },
            error: function (d) {
                layer.close(lay);
                layer.alert("请求失败请重试或检查网络！");
            }
        });
    }
}
var myLayout;
$(function () {
    myLayout = $('body').layout({
        north__minSize: 50
        , north__maxSize: 400,
        togglerContent_open: '<div class="ui-icon"></div>', togglerContent_closed: '<div class="ui-icon"></div>'
    });
    getData();
    $("#form_search").on("submit", function (e) {
        mgeRole.bsTable.destroy();
        getData();
        return false;
    });
    mgeRole.addOnClick();
    mgeRole.updateOnClick();
    mgeRole.delOnClick();
    mgeRole.postAjaxFrom();
    mgeRole.menuTree();
});

function getData() {
    var bs = new BgdataTable();
    var opt = new BgOption(mgeRole.tableid, ctx + "/mge/adx/listrole?rad=" + new Date().getTime(), mgeRole.initColumn(), mgeRole.queryParams(), mgeRole.resHeigth());
    opt.toolbarId = "table1Toolbar";
    bs.draw(opt);
    mgeRole.bsTable = bs;
}